<template>
  <div class="qustions-check">
    <el-dialog
      :title="`${data.id?'修改':'新增'}学科`"
      :visible.sync="showlog"
      width="400px"
    >
      <el-form
        ref="forms"
        size="small"
        label-width="80px"
        :model="form"
        :rules="formRules"
      >
        <el-form-item
          label="学科名称"
          prop="subjectName"
        >
          <el-input
            v-model="form.subjectName"
            placeholder="请输入学科名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="是否显示"
          prop="isFrontDisplay"
        >
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancal">取消</el-button>
        <el-button
          @click="confirm()"
          type="primary"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    data: {
      default: () => { },
      type: Object
    }
  },
  data () {
    return {
      showlog: false, // 弹框显示
      form: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      },
      formRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', tirgger: 'blur' }
        ]

      }
    }
  },
  methods: {
    open () {
      this.showlog = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.form = { id, subjectName, isFrontDisplay }
      } else {
        this.form = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.forms.clearValidate()
      })
    },
    // 点击取消
    cancal () {
      this.showlog = false
      this.$refs.forms.resetFields()
    },
    async confirm () {
      this.$refs.forms.validate(async valid => {
        if (valid) {
          if (!this.data.id) {
            // 新增
            await add(this.form)
          } else {
            // 修改
            this.form.id = this.data.id
            await update(this.form)
          }
          this.$message.success('操作成功')
          this.showlog = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
